package com.huice.base;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.apache.commons.io.FileUtils;
import org.testng.ITestResult;


/**
 * 截图
 */
public class Screenshot {

    /**
     * 截图并返回图片路径
     */
    private static void takeScreenshot(WebDriver driver, String screenPath) {
        try {
            File srcFile = ((TakesScreenshot) driver)
                    .getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(srcFile, new File(screenPath));
            System.out.print(srcFile);
        } catch (IOException e) {
            System.out.println("截图异常");
        }
    }

    /**
     * 截图并返回图片路径，自动生成图片文件名
     */
    public static String takeScreenshotToDir(WebDriver driver, String dirpath) {
        String screenname = String.valueOf(new Date().getTime()) + ".jpg";
        File dir = new File(dirpath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String screenpath = new File(dir, screenname).getAbsolutePath();
        takeScreenshot(driver, screenpath);
        return screenname;
    }


}
